package br.org.abmnet.util;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.SessionFactory;

public class ConexaoHibernateFilter implements Filter {

    private SessionFactory sf;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.sf = HibernateUtil.getSession();
    }

    @Override
    public void doFilter(ServletRequest servletFilter, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        try {
            this.sf.getCurrentSession().beginTransaction();
            chain.doFilter(servletFilter, servletResponse);
            this.sf.getCurrentSession().getTransaction().commit();
            this.sf.getCurrentSession().close();
        } catch (Throwable ex) {
            try{
                if(this.sf.getCurrentSession().beginTransaction().isActive()){
                    this.sf.getCurrentSession().beginTransaction().rollback();
                }
            }catch (Throwable tw){
                tw.printStackTrace();
            }
            throw new ServletException();
        }
    }

    @Override
    public void destroy() {
    }

}
